package cn.com.nes.site.service.system.message;

import cn.com.nes.common.em.WorkOrderNotificationEnum;
import cn.com.nes.mybatis.agent.ope.entity.IsUserPhoneInfo;
import cn.com.nes.site.entity.dto.message.AliMessage;
import cn.com.nes.site.service.workOrder.dto.BadgeCount;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.push.model.v20160801.PushRequest;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.aliyuncs.utils.ParameterHelper;
import com.google.gson.Gson;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 消息推送
 *
 * @Author: ShenWei
 * @Date: 2024/03/11/17:38
 */
@Component
@Slf4j
public class MessagePush {

    private final Map<String, Key> appKeys = new HashMap<>();

    @Resource
    MessageInfoService messageInfoService;

    @Data
    @Builder
    private static class Key {
        private long iOS;
        private long android;
    }

    public void pushWorkOrderNotification(List<IsUserPhoneInfo> devices, String workOrderId, WorkOrderNotificationEnum notificationDetail) {
        pushWorkOrderNotification(devices, workOrderId, notificationDetail, new JSONObject());
    }

    /**
     * 根据用户手机系统推送通知
     *
     * @param devices     设备id
     * @param workOrderId 工单id
     */
    public void pushWorkOrderNotification(List<IsUserPhoneInfo> devices, String workOrderId,
                                          WorkOrderNotificationEnum notificationDetail, JSONObject extraParams) {
        List<String> androidDevices = new ArrayList<>();
        List<String> iOSDevices = new ArrayList<>();
        filterDevices(devices, androidDevices, iOSDevices);
        if (CollUtil.isNotEmpty(androidDevices)) {
            pushNewWorkOrderNotification(String.join(",", androidDevices), 0, workOrderId,
                    notificationDetail, extraParams);
        }
        if (CollUtil.isNotEmpty(iOSDevices)) {
            pushNewWorkOrderNotification(String.join(",", iOSDevices), 1, workOrderId,
                    notificationDetail, extraParams);
        }
    }

    /**
     * 推送通知
     *
     * @param deviceId           设备id
     * @param deviceType         设备系统, 0-安卓, 1-iOS
     * @param workOrderId        工单id
     * @param notificationDetail 通知详情
     * @return
     */
    public PushResponse pushNewWorkOrderNotification(String deviceId, int deviceType, String workOrderId,
                                                     WorkOrderNotificationEnum notificationDetail,
                                                     JSONObject extraParams) {
        extraParams.put("workOrderId", workOrderId);
        extraParams.put("notificationType", notificationDetail.getType());
        return pushAliMessageWithBadge(deviceId, deviceType, notificationDetail.getTitle(),
                notificationDetail.getBody(), extraParams, "1");
    }

    private void filterDevices(List<IsUserPhoneInfo> devices, List<String> androidDevices, List<String> iOSDevices) {
        for (IsUserPhoneInfo device :
                devices) {
            if (device.getDeviceType() == 0) {
                androidDevices.add(device.getDeviceId());
            } else {
                iOSDevices.add(device.getDeviceId());
            }
        }
    }

    /**
     * 推送带角标信息的通知
     *
     * @param deviceId    设备id
     * @param deviceType  设备系统, 0-安卓, 1-iOS
     * @param title       标题
     * @param body        内容
     * @param extraParams 额外参数
     * @param channel     消息通道, 1-新维修工单, 2-新审核工单
     * @return
     */
    public PushResponse pushAliMessageWithBadge(String deviceId, int deviceType, String title, String body,
                                                JSONObject extraParams, String channel) {
        //查询角标信息
        BadgeCount badgeCount = messageInfoService.getBadgeCount(deviceId);
        extraParams.put("badgeCount", badgeCount);
        return pushAliMessage(AliMessage.builder()
                .deviceId(deviceId)
                .deviceType(deviceType)
                .title(title)
                .body(body)
                .extraParams(extraParams)
                .channel(channel)
                .build());
    }

    /**
     * 推送通知
     *
     * @return
     */
    public PushResponse pushAliMessage(AliMessage message) {
        message.setApp("mtpf_gcd");
        return push(message);
    }

    public PushResponse push(AliMessage message) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                "LTAI5tNM5KAEBVR9467LBBDv", "UaJznRWPVT1EABHOYhrrjkMzzoqgoX");
        IAcsClient client = new DefaultAcsClient(profile);

        PushRequest request = new PushRequest();
        request.setAppKey(message.getDeviceType() == 0
                ? appKeys.get(message.getApp()).getAndroid()
                : appKeys.get(message.getApp()).getIOS());
        request.setPushType("NOTICE");
        request.setDeviceType("ALL");
        request.setTarget("DEVICE");
        request.setTargetValue(message.getDeviceId());
        request.setBody(message.getBody());
        request.setTitle(message.getTitle());
        request.setAndroidExtParameters(message.getExtraParams().toJSONString());
        request.setIOSExtParameters(message.getExtraParams().toJSONString());
        if (message.getIOSDev() == 1) {
            request.setIOSApnsEnv("DEV");// 苹果开发环境
        }
        request.setAndroidNotificationChannel(message.getChannel());
        request.setAndroidNotifyType("BOTH");
        request.setAndroidRemind(true);
        request.setAndroidPopupTitle(message.getTitle());
        request.setAndroidPopupBody(message.getBody());
        request.setStoreOffline(true);
        request.setAndroidNotificationBarPriority(2);
        request.setAndroidPopupActivity("com.jarvanmo.rammus.PopupPushActivity");
        if (message.getExtraParams() != null && message.getExtraParams().containsKey("badgeCount")) {
            BadgeCount badgeCount = message.getExtraParams().getObject("badgeCount", BadgeCount.class);
            Integer totalCount = badgeCount.getTotalCount();
            request.setIOSBadge(totalCount);
        }
        String expireTime = ParameterHelper.getISO8601Time(new Date(System.currentTimeMillis() + 72 * 3600 * 1000));
        request.setExpireTime(expireTime);
        try {
            PushResponse response = client.getAcsResponse(request);
            log.info("消息已推送,消息内容: {},推送结果: {}", message, new Gson().toJson(response));
            return response;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        log.error("消息推送失败, 消息内容: {}", message);
        return null;
    }
}
